﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Security.Policy;
using System.Text;
using System.Web.Mvc;
using System.Web.UI;

namespace viBook.Helpers
{
    public static class HelperExtension
    {
        public static string CollectionToJavaScriptArray<T>(IEnumerable<T> values,
                                                            params Expression<Func<T, dynamic>>[] expression)
            where T : class
        {
            var sb = new StringBuilder("var ");
            sb.Append(" = [");

            foreach (T value in values)
            {
                sb.Append(string.Format("new {0}(", typeof(T).Name));
                for (int index = 0; index < expression.Length; index++)
                {
                    Expression<Func<T, dynamic>> ex = expression[index];
                    sb.Append("'");
                    //                    var v = ex.Compile()();
                    //                    sb.Append(v);
                    sb.Append(index == expression.Length - 1 ? "'" : "',");
                }
                sb.Append(")");
            }
            sb.Append("];");
            return sb.ToString();
        }

        public static string MakeAjaxCall(this UrlHelper urlHelper, string action, string controller, string customeJsonData, string callback)
        {
            var sb = new StringBuilder();
            sb.Append("function() {");
            sb.Append("$.ajax({");
            sb.Append(String.Format("url: '{0}',", urlHelper.Action(action, controller)));
            sb.Append("type: 'POST',");
            sb.Append(string.Format("data: ko.toJSON({0}),", customeJsonData));
            sb.Append("contentType: 'APPLICATION/JSON',");
            sb.Append(string.Format("success:this().{0}", callback));
            sb.Append("});");
            sb.Append("}");
            return sb.ToString();
        }
    }
}